<template>
  <el-dialog
    title="合同模板管理"
    :close-on-click-modal="false"
    :before-close="handleClose"
    append-to-body
    width="600px"
    top="60px"
    :visible.sync="visible"
  >
    <el-form label-width="120px" ref="form" :rules="rules" :model="editData">
      <el-form-item label="合同类型" prop="contract_type_code">
        <c-select
          placeholder="合同类型"
          clearable
          class="form-control-ml"
          :options="enumContractType"
          v-model="editData.contract_type_code"
        ></c-select>
      </el-form-item>
      <el-form-item label="模板标题" prop="contract_title">
        <el-input
          placeholder="合同模板标题"
          clearable
          class="form-control-ml"
          v-model="editData.contract_title"
        ></el-input>
      </el-form-item>
      <el-form-item label="模板参数(使用英文 , 号隔开)" prop="key_infos">
        <el-input
          placeholder="模板参数(使用英文 , 号隔开。每个逗号之间不能超过20字符)"
          clearable
          type="textarea"
          :rows="5"
          class="form-control-ml"
          v-model="editData.key_infos"
        ></el-input>
      </el-form-item>
      <el-form-item label="选择合同模板" prop="file">
        <label v-loading="loading">
          <span class="badge badge-primary p-2 cursor-pointer">选择文件</span>
          <input
            type="file"
            class="form-control-ml"
            accept="application/pdf"
            style="display: none"
            @change="selectFile"
          />
        </label>
        <div v-for="(p, index) of fileList" :key="index">{{ p.name }}</div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="btn-long" @click="handleSubmit" :loading="saveLoading">
          保存
        </el-button>
        <el-button class="btn-long" :loading="saveLoading" @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { enumContractType } from '@/credit/plugins/enumCadmin'
import { mapGetters } from 'vuex'
import { getData } from '@/common/api/cfca'
import { base64ToBlob } from '@/credit/views/cadmin/contract/Contract'
export default {
  components: {},
  props: {
    visible: Boolean,
    cfcaId: { type: String, default: '' },
    formData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      enumContractType,
      editData: {},
      rules: {
        contract_type_code: { required: true, message: '请选择合同类型', trigger: 'change' },
        contract_title: { required: true, message: '请输入模板标题', trigger: 'blur' },
        key_infos: { required: true, message: '请输入模板参数', trigger: 'blur' },
      },
      fileList: [],
      saveLoading: false,
      loading: false,
      action: '',
    }
  },
  computed: {
    ...mapGetters(['clientId']),
    isPut() {
      return !!this.cfcaId
    },
    contractId() {
      return this.formData ? this.formData.contract_template_id : ''
    },
  },
  watch: {
    formData: {
      handler: function () {
        this.editData = { ...this.formData }
        if (this.cfcaId) {
          this.loading = true
          this.fileList = []
          getData('contract/template', { templateId: this.cfcaId })
            .then(res => {
              const data = (res && res.data) || {}
              let fileBase = (data.contractTemplate && data.contractTemplate.data) || ''
              fileBase = `data:application/pdf;base64,${fileBase}`
              const file = base64ToBlob(fileBase)
              file.name = this.editData.contract_title + '.pdf'
              this.fileList.push(file)
            })
            .finally(() => {
              this.loading = false
            })
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {},
  methods: {
    handleClose() {
      this.fileList = []
      this.$emit('update:visible', false)
    },
    OnExceed() {
      this.$message.warning('一个合同只能对应一个模板')
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitUpload()
        } else {
          this.$message.error('输入错误，请重新填写!')
        }
      })
    },
    submitUpload() {
      if (!this.fileList.length) {
        return this.$message.warning('请选择文件')
      }
      const { contract_type_code: code, contract_title: title, key_infos: key } = this.editData
      const formData = new FormData()
      formData.append('file', this.fileList[0])
      formData.append('success_action_status', 200)
      if (this.isPut) {
        this.action = `/cfca/contract/template?contractTemplateId=${this.contractId}&templateId=${this.cfcaId}&contractTypeCode=${code}&contractTitle=${title}&keyInfos=${key}`
        this.putData(formData)
      } else {
        this.action = `/cfca/contract/template?serviceId=${this.clientId}&contractTypeCode=${code}&contractTitle=${title}&keyInfos=${key}`
        this.postData(formData)
      }
    },
    putData(formData) {
      this.$http
        .put(this.action, formData)
        .then(() => {
          this.uploadSuccess()
        })
        .catch(() => {
          this.$message.error('上传失败')
        })
    },
    postData(formData) {
      this.$http
        .post(this.action, formData)
        .then(() => {
          this.uploadSuccess()
        })
        .catch(() => {
          this.$message.error('上传失败')
        })
    },
    selectFile(e) {
      this.fileList = []
      if (e.target.files && e.target.files[0]) {
        const file = e.target.files[0]
        this.fileList.push(file)
      }
    },
    uploadSuccess() {
      this.$message.success('上传成功')
      this.handleClose()
      this.$emit('success', true)
    },
  },
}
</script>
<style lang="scss" scoped></style>
